#!/bin/csh

if ( $#argv > 1 ) then
   echo 'Usage :' $0 ccyymmddhh
   exit 1
else if ( $#argv == 0 ) then
   echo 'Usage :' $0 ccyymmddhh
   exit 1
endif
setenv runtime $1
setenv y4  `echo $runtime | cut -c1-4`
setenv y2  `echo $runtime | cut -c3-4`
setenv m2  `echo $runtime | cut -c5-6`
setenv d2  `echo $runtime | cut -c7-8`
setenv h2  `echo $runtime | cut -c9-10`

# go to system dir and set environment variables
#####################
cd /home/dataop/scripts-data/
source ./settings
setenv logfile "$logdir/gfs.$runtime.log"
###########################################

# check data status
set check = `$downscriptdir/read-status.csh $runtime check`
if ( $check == 0 ) then
else
	$downscriptdir/modify-status.csh $runtime init
endif

# set $flag_download according to $force_download_gfs and data status
msg_log "--------------------------------------------"
msg_log "BEG" `date`
msg_log "--------------------------------------------"
if ( $force_download_gfs ) then 
	set flag_download = 1
	msg_log "WARNING: FROCE-DOWNLOAD ACTIVATED"
else
	set flag = `$downscriptdir/read-status.csh $runtime gfs`
	if ( $flag == 0 ) then
		msg_log "GFS DATA $runtime WILL BE DOWNLOADED."
		set flag_download = 1
	else if ( $flag == 1 ) then
		msg_log "GFS DATA $runtime IS ALREADY DOWNLOADED."
		set flag_download = 0
	else if ( $flag == 9 ) then
	    	msg_log "GFS DATA $runtime IS BEING DOWNLOADED"
		set flag_download = 0
	endif
endif
# download

if ( $flag_download ) then
	msg_log "WRITTING DATA STATUS... 9"
	$downscriptdir/modify-status.csh $runtime gfs 9
	set server  = "http://nomads.ncep.noaa.gov/pub/data/nccf/com/gfs/prod/"
	set local   = $gfsdir
	mkdir -p $local/${y4}${m2}

	plog "DOWNLOADING GFS DATA FROM WEB SERVER..."
	msg_log "DOWNLOADING GFS DATA FROM WEB SERVER..."
    	plog "$server"
	msg_log "$server"
	@ filecount = 0
    foreach fh ( 00 06 12 18 24 30 36 42 48 54 60 66 72 )
#  WE WILL DOWNLOAD GFS 0.5-DEG FILE
        set remotefile = "$server/gfs.${y4}${m2}${d2}${h2}/gfs.t${h2}z.pgrb2f${fh}" 
        set localfile_grb2  = "$local/${y4}${m2}/gfs2_${y2}${m2}${d2}_${h2}_${fh}"
        wget "$remotefile" -O "$localfile_grb2"  -qcN
        set result = $?
        if ( $result ) then
			plog "gfs2_${y2}${m2}${d2}_${h2}_${fh} FAIL!"
            msg_log "gfs2_${y2}${m2}${d2}_${h2}_${fh} FAIL!" `date`
            \rm -f "$localfile_grb2"
        else
			plog "gfs2_${y2}${m2}${d2}_${h2}_${fh} SUCCESS!"
            msg_log "gfs2_${y2}${m2}${d2}_${h2}_${fh} SUCCESS!" `date`
			@ filecount = $filecount + 1
        endif
    end
	if ( $filecount == 13 ) then
		msg_log "WRITTING DATA STATUS... 1"
		$downscriptdir/modify-status.csh $runtime gfs 1
	else
		msg_log "WRITTING DATA STATUS... 0"
        $downscriptdir/modify-status.csh $runtime gfs 0
	endif
endif
msg_log "--------------------------------------------"
msg_log "END" `date`
msg_log "--------------------------------------------"
exit 0
